package com.ophiux.common.data.tenant;

import cn.hutool.core.util.StrUtil;
import com.ophiux.common.data.constants.CommonConstants;
import com.ophiux.common.data.headers.HeaderParams;
import com.ophiux.common.data.headers.HeaderParamsContextHolder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @desc: 请求头参数拦截
 * @author: hhl
 * @date：2023/1/29 14:35
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantContextHolderFilter extends GenericFilterBean {

	@Override
	@SneakyThrows
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		String headerTenantId = request.getHeader(CommonConstants.TENANT_ID);
		String headerAccessToken = request.getHeader(CommonConstants.TOKEN);
		String paramAccessToken = request.getParameter(CommonConstants.TOKEN);
		String paramTenantId = request.getParameter(CommonConstants.TENANT_ID);
		String headerUserClientType = request.getHeader(CommonConstants.USER_CLIENT_TYPE);
		String paramUserClientType = request.getParameter(CommonConstants.USER_CLIENT_TYPE);

		HeaderParams headerParams = new HeaderParams();
		headerParams.setUserClientType(headerUserClientType == null ? paramUserClientType : headerUserClientType);
		headerParams.setAccessToken(headerAccessToken == null ? paramAccessToken : headerAccessToken);

		if (StrUtil.isNotBlank(headerTenantId)) {
			TenantContextHolder.setTenantId(Long.parseLong(headerTenantId));
			headerParams.setTenantId(Long.parseLong(headerTenantId));
		} else if (StrUtil.isNotBlank(paramTenantId)) {
			TenantContextHolder.setTenantId(Long.parseLong(paramTenantId));
			headerParams.setTenantId(Long.parseLong(paramTenantId));
		} else {
			log.info("Header中获取tenantId=null,不设置默认tenantId");
			TenantContextHolder.setTenantId(1L);
//			throw new RuntimeException("租户不能为空");
		}

		HeaderParamsContextHolder.setHeaderParams(headerParams);
		log.info("接口:{},请求拦截：租户={}，userType={}", request.getRequestURI(), TenantContextHolder.getTenantId(), HeaderParamsContextHolder.getHeaderParams().getUserClientType());

		filterChain.doFilter(request, response);
		//清除缓存
		TenantContextHolder.clear();
		HeaderParamsContextHolder.clear();
	}

}
